package org.wattdepot.cli.command;

import java.util.ArrayList;
import java.util.List;
import java.util.ListIterator;
import org.wattdepot.client.BadXmlException;
import org.wattdepot.client.MiscClientException;
import org.wattdepot.client.NotAuthorizedException;
import org.wattdepot.resource.source.jaxb.Source;

/**
 * Retrives and lists all of the sources in the wattdepot server.
 * 
 * @author Alex Kan and Kelvin Green
 * @version 2.0
 */
public class WattDepotListSourcesCommand extends WattDepotCommand {
  /**
   * Prints a list of all the sources in the wattdepot server.
   * 
   * @param args contains an array of strings created from the user input.
   * @return String of information about sources.
   */
  public String doCommand(String args[]) {
    if (args.length < 1 || args.length > 1) { //Checks for correct input
      return "Correct command is sources.";
    }
    return getSources();
  }

  /**
   * Gets the info of the org.wattdepot.resource.source.jaxb.Source and returns to the client.
   * 
   * @return a string variable named output containing all the output for the method.
   */
  private String getSources() {
    String output = "";
    boolean error = false;
    ArrayList<String> outputArray = new ArrayList<String>();
    try {
      List<Source> sources = getClient().getSources();
      ListIterator<Source> li = sources.listIterator();
      outputArray.add("Name      Parent      Description" + cr);
      while (li.hasNext()) {
        Source curr = li.next();
        outputArray.add(curr.getName() + "   ");
        ListIterator<Source> lit = sources.listIterator();
        while (lit.hasNext()) {
          Source current = lit.next();
          ArrayList<String> ssList = (ArrayList<String>)getSubSources(current);
          try {
            ListIterator<String> ssIterator = ssList.listIterator();
            while (ssIterator.hasNext()) {
              String next = ssIterator.next();
              if (next.endsWith(curr.getName())) {
                outputArray.add(current.getName());
              }
            }

          }
          catch (Exception e) {
            error = true;
          }
        }
        outputArray.add("   " + curr.getDescription() + cr);

      }
    }
    catch (MiscClientException mce) {
      return CON_NOT_FOUND;
    }
    catch (BadXmlException bxe) {
      error = true;
    }
    catch (NotAuthorizedException nae) {
      error = true;
      if (error) {
        return "Should not happen.";
      }
    }
    catch (Exception e) {
      error = true;
    }
    output = outputArray.toString();
    output = output.replace(",", "");
    output = output.replace("[", "");
    output = output.replace("]", " ");

    return output;
  }

}
